package com.llsydn.service.local;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.llsydn.hello.R;

/**
 * @author lilinshen
 * @title LocalService本地服务
 * @description 请填写相关描述
 * @date 2018/9/29 10:59
 */
public class LocalServiceActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_service);
    }

    //启动服务
    public void startLocalService(View view) {
        Intent intent = new Intent(this, LocalService.class);
        startService(intent);
        Toast.makeText(this, "start service", Toast.LENGTH_SHORT).show();
    }

    //停止服务
    public void stopLocalService(View view) {
        Intent intent = new Intent(this, LocalService.class);
        stopService(intent);
        Toast.makeText(this, "stop service", Toast.LENGTH_SHORT).show();
    }

    private ServiceConnection connection;

    //绑定服务
    public void bindLocalService(View view) {
        Intent intent = new Intent(this, LocalService.class);
        //创建连接对象
        if (connection == null) {
            connection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    Log.e("TAG", "onServiceConnected()");
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {
                    Log.e("TAG", "onServiceDisconnected()");
                }
            };
            //绑定service
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
            Toast.makeText(this, "bind service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已经bind service", Toast.LENGTH_SHORT).show();
        }
    }

    //解绑服务
    public void unbindLocalService(View view) {
        if (connection != null) {
            unbindService(connection);
            connection = null;
            Toast.makeText(this, "unbind service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "还没有bind service", Toast.LENGTH_SHORT).show();
        }

    }

    //退出Activity，解绑服务
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connection != null) {
            unbindService(connection);
            connection = null;
        }
    }
}
